package com.ming.transaction.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.Query;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ming.transaction.common.Result;
import com.ming.transaction.entity.Image;
import com.ming.transaction.entity.User;
import com.ming.transaction.exception.ServiceException;
import com.ming.transaction.mapper.ImageMapper;
import com.ming.transaction.service.IImageService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ming.transaction.util.jwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;

import static com.ming.transaction.common.Constant.Filetype;

/**
 * <p>
 *    商品头像上传类
 * </p>
 *
 * @author 陈仕健
 * @since 2023-05-04
 */
@Service
public class ImageServiceImpl extends ServiceImpl<ImageMapper, Image> implements IImageService {

    @Value("${files.upload.path}")
    private String fileUpLoadPath;

    @Resource
    private HttpServletRequest request;

    @Resource
    private HttpServletResponse response;

    /**
     * 文件上传
     * @param file
     * @return
     * @throws IOException
     */
    @Override
    public Result uploadImage(MultipartFile file) throws IOException {
        // 获取文件名称
        String originalFilename = file.getOriginalFilename();

        // 获取文件类型
        String type = FileUtil.extName(originalFilename);

        if (!Filetype(type)) {
            throw new ServiceException(405, "图片格式不正确!");
        }
        // 获取文件大小
        long size = file.getSize();

        // 文件存储到磁盘
        File uploadParentFile = new File(fileUpLoadPath);
        // 判断配置的文件目录是否存在，若不存在则创建一个新的文件目录
        if (!uploadParentFile.exists()) {
            uploadParentFile.mkdirs();
        }

        // 定义一个文件唯一的标识位
        String uuid = IdUtil.fastSimpleUUID();
        String uurl = uuid + StrUtil.DOT + type;
        // 实际图片路径
        File uploadFile = new File(fileUpLoadPath + uurl);
        // 把获取到的文件存储到磁盘目录
        file.transferTo(uploadFile);

        // 文件路径
        String url = "http://localhost:9090/image/" + uurl;

        // 获取商品ID
        String ProId = "";
        // 将数据插入数据库

        Image image = new Image();
        image.setName(originalFilename);
        image.setType(type);
        image.setSize(size / 1024);
        image.setUrl(url);
        image.setProId(ProId);
        save(image);
        return Result.success("上传成功", url);

        // 获取当前用户账号信息
        //String number = (String) request.getSession().getAttribute("Number");
        // 根据用户账号查询该用户是否拥有头像
        // 有，上传头像时更新数据库，没有，直接保存数据
        //QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        //queryWrapper.eq("number", number);
        //// 判断是否存在 , 若存在则更新该数据
        //if (image != null) {
        //    // 更新数据
        //    image.setName(originalFilename);
        //    image.setType(type);
        //    image.setSize(size / 1024);
        //    image.setUrl(url);
        //    saveOrUpdate(image);
        //} else {
        //    // 存储到数据库
        //    Image saveImge = new Image();
        //    saveImge.setName(originalFilename);
        //    saveImge.setType(type);
        //    saveImge.setSize(size / 1024);
        //    saveImge.setUrl(url);
        //    saveImge.setUserId(use_id);
        //    save(saveImge);
        //}
    }

    /**
     * 图片获取
     * @param fileUUID
     * @throws IOException
     */
    @Override
    public void dowmloadImage(String fileUUID) throws IOException {
        // 根据文件的唯一标识码获取文件
        File dowmImage = new File(fileUpLoadPath + fileUUID);
        response.setDateHeader("Expires",0);
        response.addHeader("Pragma","no-cache");
        response.setContentType("image/jpeg");
        ServletOutputStream os = response.getOutputStream();
        os.write(FileUtil.readBytes(dowmImage));
        os.flush();
        os.close();
    }


}
